package com.hzhjhh.view.cashierView;

import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Objects;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.apache.commons.lang3.StringUtils;

import com.hzhjhh.dto.MerchandiseDTO;
import com.hzhjhh.entity.Merchandise;
import com.hzhjhh.mapper.MerchandiseMapper;
import com.hzhjhh.util.DBUtils;

/**
 * 组件初始化-收银页面-商品编号
 * @author 12083
 *
 */
public class MerchandiseCodeInit {

	private static MerchandiseMapper merchandiseMapper = DBUtils.getSqlSession(true).getMapper(MerchandiseMapper.class);
	/**
	 * 初始化商品编号-标签
	 * @return
	 */
	public static JLabel initLabel() {
		JLabel merchandiseCode = new JLabel();
		merchandiseCode.setText("商品编号");
		merchandiseCode.setBounds(30, 463, 60, 15);
		return merchandiseCode;
	}
	
	/**
	 * 初始化商品编号-输入框
	 * 
	 * @param txfPriceOne 商品单价输入框
	 */
	public static JTextField initTxf(JTextField txfPriceOne) {
		JTextField txfMerchandiseCode = new JTextField();
		txfMerchandiseCode.setFont(new java.awt.Font("宋体", Font.PLAIN, 20));
		txfMerchandiseCode.setBounds(new Rectangle(91, 460, 152, 21));
		// 添加失焦事件
		txfMerchandiseCode.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				
				queryDB(txfMerchandiseCode, txfPriceOne);
			}
		});
		// 添加按键事件：输入回车，与失焦执行一样的操作
		txfMerchandiseCode.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					queryDB(txfMerchandiseCode, txfPriceOne);
				}
			}
		});
		return txfMerchandiseCode;
	}
	
	/**
	 * 查询数据库，并赋值
	 * 
	 * @param txfMerchandiseCode 商品编码输入框
	 * @param txfPriceOne 商品单价输入框
	 */
	private static void queryDB(JTextField txfMerchandiseCode, JTextField txfPriceOne) {
		String merchandiseCode = txfMerchandiseCode.getText();
		if (StringUtils.isNotBlank(merchandiseCode)) {
			MerchandiseDTO merchandiseDTO = new MerchandiseDTO();
			merchandiseDTO.setMerchandiseTreatyCode(merchandiseCode);
			Merchandise merchandise = merchandiseMapper.selectOneByDTO(merchandiseDTO);
			if (Objects.isNull(merchandise)) {
				JOptionPane.showMessageDialog(txfMerchandiseCode, "商品不存在", "错误", JOptionPane.ERROR_MESSAGE);
				return;
			}
			txfPriceOne.setText(merchandise.getMerchandiseRetailPrice().toString()); // 单价
		}
	}
}
